<template>
	<view>

		<u-status-bar bgColor="#FFF"></u-status-bar>

		<view class="content">

			<view class="head">
				<u-tabs :scrollable="true" :current="tabIndex" :list="tabList" @change="tabClick" lineWidth="15"
					lineHeight="5" bgColor="#fff" lineColor="#f56c6c"
					:activeStyle="{color: '#303133',transform: 'scale(1.6)',fontWidth: 'bold'}"
					:inactiveStyle="{color: '#606266',transform: 'scale(1)',fontSize: '16px'}"
					itemStyle="padding-left: 25px; padding-right: 15px; height: 55px;">
				</u-tabs>
			</view>

			<view class="classify-box" @click="this.classifyFlag = !this.classifyFlag">
				<u-transition :duration="1000" :mode="'fade-up'" :show="!classifyFlag">
					<u-icon size="28" name="grid"></u-icon>
				</u-transition>
				<u-transition :duration="1000" :mode="'fade-up'" :show="classifyFlag">
					<u-icon size="28" name="list"></u-icon>
				</u-transition>
			</view>

			<scroll-view style="height: 90vh;marginTop: 5vh;marginBottom: 5vh;" scroll-y="true" refresher-enabled="true"
				:scroll-x="true" :refresher-triggered="triggered" :refresher-threshold="105" :lower-threshold="100"
				@refresherpulling="onPulling" @scrolltolower="scrolltolower" @refresherrefresh="onRefresh"
				@refresherrestore="onRestore" @refresherabort="onAbort">
				<view class="grad">
					<view class="grad-item" @click="navaTo('/errand/errandRank/errandRank')">
						<u--image :showLoading="true" src="https://abc.apricity.asia/public/icon/rank.png" width="40px"
							height="40px" @click="click"></u--image>
						<view class="grad-item-text">
							排行榜
						</view>
					</view>
				</view>

				<view class="u-page" v-if="tabIndex === 0">
					<block v-if="!classifyFlag">
						<view class="u-demo-block" v-for="(item,index) in errandList" :key="item.id">
							<view class="u-demo-block__title">
								<view class="top-left-button">
									<u-tag size="mini" text="已完成" shape="circle" type="success"
										v-if="item.is_complete === '1'"></u-tag>
									<u-tag size="mini" text="正在帮助" shape="circle" type="warning"
										v-else-if="item.is_complete === '2'"></u-tag>
									<u-tag size="mini" text="等待帮助" shape="circle" type="error" v-else></u-tag>
									<u-tag size="mini" text="帮送" shape="circle" type="success"
										v-if="item.methods === '0'"></u-tag>
									<u-tag size="mini" text="快递代拿" shape="circle" type="success"
										v-if="item.methods === '1'"></u-tag>
									<u-tag size="mini" text="帮买" shape="circle" type="success"
										v-if="item.methods === '2'"></u-tag>
									<u-tag size="mini" text="帮拿" shape="circle" type="success"
										v-if="item.methods === '3'"></u-tag>
									<u-tag size="mini" text="其他跑腿" shape="circle" type="success"
										v-if="item.methods === '4'"></u-tag>	
								</view>
								<view class="top-right-time">
									{{$u.timeFormat((new Date(item.time.replace(new RegExp("-","gm"),"/"))).getTime())}}
								</view>
							</view>
							<view class="u-demo-block__content">
								<view class="album">
									<view>
										<u--image
											:src="item.pb_info ? item.pb_info : 'https://abc.apricity.asia/public/icon/1.jpg'"
											mode="aspectFit" height="40px" width="40px" :fade="true" duration="450"
											:shape="'circle'"></u--image>
									</view>
									<view class="album__content">
										<u--text :text="'跑腿信息: ' + item.help_information" size="14"></u--text>
										<u--text margin="0 0 0 0" :text="'起点: ' + item.pick_location" size="14">
										</u--text>
										<u--text margin="0 0 0 0"
											:text="'目的地: ' + JSON.parse(item.address).address + JSON.parse(item.address).area"
											size="14"></u--text>
										<u--text v-if="item.sex === '0'" :text="'性别限制: 男女不限'" size="14"></u--text>
										<u--text v-if="item.sex === '1'" :text="'性别限制: 男'" size="14"></u--text>
										<u--text v-if="item.sex === '2'" :text="'性别限制: 女'" size="14"></u--text>
										<u--text v-if="item.methods === '1'" margin="0 0 0 0"
											:text="'快递重量: ' + item.postmethods" size="14"></u--text>
										<u--text size="12" text="详细信息已隐藏"></u--text>
										<u--text size="17" type="error" mode="price" :text="item.money"></u--text>
										<view class="errand-btn">
											<view class="errand-btn-left">
											</view>
											<view class="errand-btn-right" v-if="item.is_complete === '0'">
												<u-button @click="userConfirmErrand(item.id)" type="primary"
													shape="circle" size="mini" text="确认接单"></u-button>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</block>
					<block v-else>
						<view class="u-demo-block" v-for="(item,index) in list" :key="item.id">
							<view class="u-demo-block__title">
								<view class="top-left-button">
									<u-tag size="mini" text="已完成" shape="circle" type="success"
										v-if="item.is_complete === '1'"></u-tag>
									<u-tag size="mini" text="正在帮助" shape="circle" type="warning"
										v-else-if="item.is_complete === '2'"></u-tag>
									<u-tag size="mini" text="等待帮助" shape="circle" type="error" v-else></u-tag>
								</view>
								<view class="top-right-time">
									{{$u.timeFormat((new Date(item.time.replace(new RegExp("-","gm"),"/"))).getTime())}}
								</view>
							</view>
							<view class="u-demo-block__content">
								<view class="album">
									<view>
										<u--image
											:src="item.pb_info ? item.pb_info : 'https://abc.apricity.asia/public/icon/1.jpg'"
											mode="aspectFit" height="40px" width="40px" :fade="true" duration="450"
											:shape="'circle'"></u--image>
									</view>
									<view class="album__content">
										<u--text :text="'跑腿信息:' + item.help_information" size="14"></u--text>
										<u--text margin="0 0 0 0" :text="'起点:' + item.pick_location" size="14">
										</u--text>
										<u--text margin="0 0 0 0"
											:text="'目的地:' + JSON.parse(item.address).address + JSON.parse(item.address).area"
											size="14"></u--text>
										<u--text size="12" text="详细信息已隐藏"></u--text>
										<u--text size="17" type="error" mode="price" :text="item.money"></u--text>
										<view class="errand-btn">
											<view class="errand-btn-left">
											</view>
											<view class="errand-btn-right" v-if="item.is_complete === '0'">
												<u-button @click="userConfirmErrand(item.id)" type="primary"
													shape="circle" size="mini" text="确认接单"></u-button>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</block>
				</view>
				<view class="bottom">
					<u-loadmore :status="status" :icon="true" v-if="isShow" :loadingText="loadingText"
						@loadmore="loadmore" />
				</view>
			</scroll-view>

		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabList: [{
					name: '跑腿'
				}],
				tabIndex: 0,
				errandList: [],
				errandPage: 1,
				errandBtnFlag: true,
				triggered: false,
				_freshing: false,
				status: 'loadmore',
				isShow: false,
				list: [],
				listPage: 1,
				listFlag: true,
				classifyFlag: false,
				code: ''
			};
		},
		onLoad() {
			this.getCode()
			this.isShow = false
			this._freshing = false;
			// this.getErrandData()
			this.getAllHelpFun()
			this.triggered = true;
			this.isShow = true
			this.judgeIs()
		},
		methods: {
			navaTo (url) {
				uni.navigateTo({
					url: url
				})
			},
			// get code
			getCode() {
				wx.login({
					success: (res) => {
						this.code = res.code
					}
				})
			},
			// 默认给后台发一次请求,判断是否为骑士
			judgeIs() {
				let _this = this
				uni.request({
					url: 'https://www.apricity.asia:8911/apply/judgeUserIs',
					header: {
						Authorization: uni.getStorageSync('token') || ''
					},
					success: (res) => {
						if (res.data.status !== 200) return
						// 是骑士,根据时间来判断是否弹出骑士接单的框
						const time = uni.getStorageSync('time') || ''
						let old_time = new Date();
						if (time.length === 0) { // 没有直接弹出
							uni.showModal({
								title: '订阅跑腿订单通知',
								content: '您是否订阅新的跑腿订单通知?以便有单时我们提醒您',
								success: (res) => {
									if (res.confirm) {
										_this.subscrShop(
											'xqyOWGL_3P5Oaiqwb2kqUuZ3JuFwvuwcU3UuAJIKoNE')
										uni.setStorage({
											key: 'time',
											data: old_time
										})
									} else {
										uni.setStorage({
											key: 'time',
											data: old_time
										})
									}
								}
							})
						} else {
							// 有
							let new_time = Date.parse(new Date());
							let new_time2 = Date.parse(time);
							console.log((new_time - new_time2) / (60 * 60 * 1000))
							if ((new_time - new_time2) / (60 * 60 * 1000) >= 0.05) { // 有半个小时了
								uni.showModal({
									title: '订阅跑腿订单通知',
									content: '您是否订阅新的跑腿订单通知?以便有单时我们提醒您',
									success: (res) => {
										let old_time = new Date();
										if (res.confirm) {
											_this.subscrShop(
												'xqyOWGL_3P5Oaiqwb2kqUuZ3JuFwvuwcU3UuAJIKoNE')
											uni.setStorage({
												key: 'time',
												data: old_time
											})
										} else {
											uni.setStorage({
												key: 'time',
												data: old_time
											})
										}
									}
								})
							}
						}
					}
				})
			},
			/*
				订阅
			*/
			subscrShop(tplids) {
				uni.requestSubscribeMessage({
					tmplIds: [tplids],
					success: async (res) => {
						if (res[tplids] !== 'accept') return
						let prames = {
							code: this.code,
							template_id: tplids
						}
						const {
							data: res2
						} = await uni.$http.post('/message/addWenXinMessage', prames)
						console.log(res2)
						if (res2.status !== 200) return uni.showToast({
							icon: 'none',
							title: '订阅失败',
							duration: 2000
						})
						uni.showToast({
							icon: 'none',
							title: '订阅成功',
							duration: 2000
						})
					},
					fail: (res) => {
						console.log(res)
					},
					complete: (res) => {

					}
				})
			},
			// 只获取需要帮助的
			async getAllHelpFun() {
				try {
					this.status = 'loading';
					const {
						data: res
					} = await uni.$http.get(`/order/getAllOrderMessage/${this.listPage}`)
					console.log(res)
					if (res.status !== 200) return uni.showToast({
						title: '获取订单信息失败,请登录后尝试',
						duration: 1500,
						icon: 'none'
					})
					if (res.data.total === 0) return this.status = 'nomore';
					this.status = 'loadmore';
					this.list = [...this.list, ...res.data]
					this.listPage++
				} catch (e) {
					uni.showToast({
						icon: 'none',
						title: e,
						duration: 2000
					})
				}
			},
			scrolltolower() {
				if (this.tabIndex === 0 && this.classifyFlag) {
					uni.$u.throttle(this.getAllHelpFun, 500)
				} else if (this.tabIndex === 0) {
					uni.$u.throttle(this.getErrandData, 500)
				} else if (this.tabIndex === 1) {
					uni.$u.throttle(this.getWorkData, 500)
				}
			},
			loadmore() {
				if (this.tabIndex === 0 && this.errandList.length === 0) {
					this.loadmoreText = '没有更多了'
				}
				if (this.tabIndex === 0 && this.classifyFlag && this.list.length === 0) {
					this.loadmoreText = '没有更多了'
				}
			},
			onPulling(e) {

			},
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				this.isShow = false
				if (this.tabIndex === 0 && this.classifyFlag) {
					this.list = []
					this.listPage = 1
					this.getAllHelpFun()
					this.triggered = false;
					this._freshing = false;
				} else if (this.tabIndex === 0) {
					this.errandList = []
					this.errandPage = 1
					this.getErrandData()
					this.triggered = false;
					this._freshing = false;
				}
				this.isShow = true
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
				console.log("onRestore");
			},
			onAbort() {
				console.log("onAbort");
			},
			// tab切换
			tabClick(tabParams) {
				this.tabIndex = tabParams.index
				if (this.workList.length === 0) {
					uni.$u.throttle(this.getWorkData, 500, false)
				}
			},
			// 获取跑腿数据
			async getErrandData() {
				this.status = 'loading';
				const {
					data: res
				} = await uni.$http.get(`/order/getordermessage/${this.errandPage}`)
				if (res.status !== 0) return uni.showToast({
					title: '获取全部的订单信息失败,请登录后尝试',
					duration: 1500,
					icon: 'none'
				})
				if (res.data.length === 0) return this.status = 'nomore';
				console.log(res.data)
				this.status = 'loadmore';
				this.errandList = [...this.errandList, ...res.data]
				this.errandPage++
			},
			// 骑士确认接单
			userConfirmErrand(id) {
				uni.showModal({
					title: '接单?',
					content: '您真的要接这个单吗?，请确保自己已经为骑士',
					success: async (res) => {
						if (res.confirm) {
							const {
								data: res
							} = await uni.$http.get(`/order/userapply/${id}`)
							if (res.status !== 0) return uni.showToast({
								title: res.message,
								duration: 1500,
								icon: 'none'
							})
							uni.showModal({
								title: '接单成功',
								content: '是否立即前往跑腿接单查看接单信息',
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url: '/errand/errandCenter/errandCenter'
										})
									}
								}
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.classify-box {
		position: fixed;
		right: 3%;
		top: 15%;
		z-index: 999;
	}

	.bottom {
		padding: 10rpx 0;
	}

	.head {
		background: #FFF;
	}

	.errand-btn {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.u-demo-block__title {
		padding-right: 10px;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.top-left-button {
			display: flex;

			width: 60px;
			margin-bottom: 5px;
		}

		.top-right-time {
			color: #909399;
			font-size: 13px;
		}
	}

	.u-page {
		width: 95%;
		margin: 10px 2%;
	}

	.u-demo-block {
		margin-top: 10px;
		padding: 10px 5px;
		border-radius: 5px;
		background-color: #FFF;
		box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
	}

	page {
		background-color: #f8f8f8;
	}

	.album {
		@include flex;
		align-items: flex-start;

		&__avatar {
			background-color: $u-bg-color;
			padding: 5px;
			border-radius: 3px;
		}

		&__content {
			margin-left: 10px;
			flex: 1;
		}
	}

	.grad {
		margin: 20px 2%;
		width: 95%;
		background: #FFF;
		box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
		border-radius: 5px;
		padding: 10px;
		& .grad-item {
			display: flex;
			align-items: left;
			justify-content: center;
			flex-direction: column;
			& .grad-item-text {
				font-size: 14px;
				color: #303133;
			}
		}
	}
</style>
